package com.apac.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.apac.bom.User;
import com.apac.dao.UserDAO;

public class SessionCheckInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		String username = request.getRemoteUser();
		String requestURI = request.getRequestURI();
		
//		System.out.println(request.getRemoteUser());
//		System.out.println(user);
//		System.out.println(requestURI.substring(requestURI.length()-5));
		
		if(user!=null){
			return true;
		}
		else if(user==null && username==null && "login".equals(requestURI.substring(requestURI.length()-5))){
			return true;
		}
		else if(user==null && username!=null){
			UserDAO userDAO = new UserDAO();
			user = (User) userDAO.findByUserName(request.getRemoteUser());
			session.setAttribute("user", user);
			return true;
		}
		else{
			return false;
		}
	}

}
